import 'package:e_reception_flutter/colors/colors.dart';
import 'package:e_reception_flutter/common_widgets/common_confirm_cancel_dialog/common_confirm_cancel_dialog.dart';
import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/singleton/user_repository/user_repository.dart';
import 'package:e_reception_flutter/ui/company/choose_city/bean/choose_city_list_item_bean.dart';
import 'package:e_reception_flutter/ui/company/company_detail/bean/company_address_bean.dart';
import 'package:e_reception_flutter/ui/company/company_detail/bean/company_detail_response_bean.dart';
import 'package:e_reception_flutter/ui/company/company_detail/bean/independent_company_basic_info_bean.dart';
import 'package:e_reception_flutter/ui/company/company_detail/class_or_department/class_or_department_page.dart';
import 'package:e_reception_flutter/ui/company/company_detail/event/refresh_company_detail_page_event.dart';
import 'package:e_reception_flutter/ui/company/manager/manager_list_page.dart';
import 'package:e_reception_flutter/ui/company/unactive_person/unactive_list_page.dart';
import 'package:e_reception_flutter/utils/address_about_utils.dart';
import 'package:e_reception_flutter/utils/app_overall_distinguish.dart';
import 'package:e_reception_flutter/utils/router_utils.dart';
import 'package:e_reception_flutter/utils/screen_utils.dart';
import 'package:e_reception_flutter/utils/vg_global_func.dart';
import 'package:e_reception_flutter/utils/vg_location_utils.dart';
import 'package:e_reception_flutter/utils/vg_role_utils.dart';
import 'package:e_reception_flutter/utils/vg_string_utils.dart';
import 'package:e_reception_flutter/vg_widgets/clip_image_head_border/clip_image_head_border_utils.dart';
import 'package:e_reception_flutter/vg_widgets/vg_dialog_widget/pop_window.dart';
import 'package:e_reception_flutter/vg_widgets/vg_image_widget/vg_cache_net_work_image.dart';
import 'package:e_reception_flutter/vg_widgets/vg_top_bar_widget/vg_top_bar_widget.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:matisse_android_plugin/export_matisse.dart';
import 'package:vg_base/vg_arch_lib.dart';
import 'package:vg_base/vg_evnet_bus_lib.dart';
import 'package:vg_base/vg_permission_lib.dart';
import 'package:vg_base/vg_string_util_lib.dart';
import 'package:vg_flutter_base_moudle/vg_moudle_widget_lib.dart';

import '../company_basic_data_view_model.dart';
import '../company_detail_view_model.dart';
import '../enterprise_detail_page.dart';
import 'company_more_pop_window.dart';

/// 公司详情组件
///
/// @author: zengxiangxi
/// @createTime: 3/22/21 5:51 PM
/// @specialDemand:
class CompanyDetailInfoWidget extends StatefulWidget {
  final CompanyBasicInfoBean companyBasicInfoBean;
  final CompanyDetailDataBean infoBean;
  final GlobalKey popKey;
  final String defaultgps;

  const CompanyDetailInfoWidget({Key key, this.infoBean, this.popKey, this.companyBasicInfoBean, this.defaultgps})
      : super(key: key);

  @override
  _CompanyDetailInfoWidgetState createState() => _CompanyDetailInfoWidgetState();
}

class _CompanyDetailInfoWidgetState extends BaseState<CompanyDetailInfoWidget> {

  CompanyBasicDataViewModel _viewModel;

  @override
  void initState() {
    super.initState();
    _viewModel = CompanyBasicDataViewModel(this,widget?.defaultgps);
    _viewModel.getCompanyBasicInfo();
    VgEventBus.global.streamController.stream.listen((event) {
      if (event is RefreshCompanyDetailPageEvent) {
        print('_TerminalDetailInfoPageState' + event.toString());
        _viewModel.getCompanyBasicInfo();
      }
    });
  }
  @override
  Widget build(BuildContext context) {
    return Container(
      margin: const EdgeInsets.symmetric(horizontal: 15, vertical: 12),
      height: 125,
      child: Column(
        children: <Widget>[
          Container(
            height: 80,
            decoration: BoxDecoration(
                color: Color(0xFF3A3F50),
                borderRadius: BorderRadius.only(
                    topLeft: Radius.circular(12.0),
                    topRight: Radius.circular(12))),
            child: _toMainRowWidget(),
          ),
          (widget.infoBean?.companyInfo?.isCompany()??true)? _cntCompanyWidget() : _cntOrgWidget()
        ],
      ),
    );
  }

  Widget _toMainRowWidget() {
    return Row(
      children: <Widget>[
        SizedBox(
          width: 12,
        ),
        GestureDetector(
          behavior: HitTestBehavior.translucent,
          onTap: () {
            if (StringUtils.isEmpty(widget.companyBasicInfoBean?.companylogo ?? "")) {
              if (!VgRoleUtils.isSuperAdmin(UserRepository.getInstance().getCurrentRoleId())) {
                EnterpriseDetailPage.navigatorPush(context, widget?.defaultgps, itemBean: widget?.companyBasicInfoBean);
                return;
              }
              _chooseSinglePicAndClip();
              return;
            }
            CompanyPicDetailPage.navigatorPush(context,
                url: widget.companyBasicInfoBean?.companylogo,
                selectMode: SelectMode.Normal,
                clipCompleteCallback: (path, cancelLoadingCallback) {
                  widget.companyBasicInfoBean?.companylogo = path;
                  // setState(() {});
                  _viewModel.setCompanyPic(
                      context, widget.companyBasicInfoBean?.companylogo,
                      widget.companyBasicInfoBean?.companyid);
                });
          },
          child: ClipRRect(
            borderRadius: BorderRadius.circular(4),
            child: Container(
              width: 56,
              height: 56,
              decoration: BoxDecoration(color: Colors.white),
              child: VgCacheNetWorkImage(
                widget.companyBasicInfoBean?.companylogo ?? "",
                imageQualityType: ImageQualityType.middleUp,
                fit: BoxFit.contain,
                errorWidget:
                    Image.asset("images/company_detail_card_info_logo_ico.png"),
                placeWidget:
                    Image.asset("images/company_detail_card_info_logo_ico.png"),
              ),
            ),
          ),
        ),
        Container(
          width: 14,
        ),
        Expanded(
          child: Container(
            height: 56,
            child: _toMainColumnWidget(),
          ),
        ),
        // Offstage(
        //   offstage: (widget?.companyBasicInfoBean?.addressCnt ?? 0) < 2,
        //   child: Container(
        //     child: Text("${widget?.companyBasicInfoBean?.addressCnt ?? 0}",
        //         style: TextStyle(
        //           fontSize: 12,
        //           color: ThemeRepository.getInstance()
        //               .getHintGreenColor_5E687C(),
        //     )),
        //   ),
        // ),
        // SizedBox(
        //   width: 9,
        // ),
        Image.asset(
          "images/go_ico.png",
          width: 6,
          color: Colors.grey,
        ),
        SizedBox(
          width: 15,
        ),
      ],
    );
  }

  void _chooseSinglePicAndClip() async {
    String fileUrl =
    await MatisseUtil.clipOneImage(context,
        scaleX: 1, scaleY: 1,
      isCanSelectRadio: true,
        onRequestPermission: (msg)async{
          bool result =
          await CommonConfirmCancelDialog.navigatorPushDialog(context,
            title: "提示",
            content: msg,
            cancelText: "取消",
            confirmText: "去授权",
          );
          if (result ?? false) {
            PermissionUtil.openAppSettings();
          }
        }
    );
    if (fileUrl == null || fileUrl == "") {
      return null;
    }
    widget.companyBasicInfoBean?.companylogo = fileUrl;
    _viewModel.setCompanyPic(context, widget.companyBasicInfoBean?.companylogo,
        widget.companyBasicInfoBean?.companyid);
  }

  Widget _toMainColumnWidget() {
    ////1、企业有详细地址门牌：展示企业简称、区县、详细门牌地址；
    ////2、企业无详细地址门牌：展示企业简称、企业全称（无全称显示暂无全称）、区县。
    // bool hasAddress=StringUtils.isNotEmpty(widget.companyBasicInfoBean?.userAddress);
    //1、企业有区县地址：展示企业简称、区县、详细门牌地址；
    //2、企业无区县地址：展示企业简称、企业全称（无全称显示暂无全称）、暂无区县。

    // bool hasCity = StringUtils.isNotEmpty(widget.companyBasicInfoBean?.userCity);
    return Column(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: <Widget>[
        Container(
          alignment: Alignment.centerLeft,
          child: Text(
            showOriginEmptyStr(widget.companyBasicInfoBean?.companynick) ?? "-",
            maxLines: 1,
            overflow: TextOverflow.ellipsis,
            style: TextStyle(
              color: Colors.white,
              fontSize: 15,
              fontWeight: FontWeight.w600,
            ),
          ),
        ),
        Container(
          alignment: Alignment.centerLeft,
          child: Text(
            AddressAboutUtils.getAddressStr()?? "-",
            // _getNewAddress(false) ?? "-",
            // hasCity ? (_getNewAddress(false) ?? "-") : (showOriginEmptyStr(widget.companyBasicInfoBean?.companyname) ?? "暂无全称"),
            maxLines: 1,
            overflow: TextOverflow.ellipsis,
            style: TextStyle(
              color: Color(0xFFBFC2CC),
              fontSize: 11,
            ),
          ),
        ),
        Container(
          alignment: Alignment.centerLeft,
          child: Text(
            "${UserRepository.getInstance().userData?.companyInfo?.address ?? ''}",
            // _getNewAddress(true) ?? "-",
            // hasCity ? (_getNewAddress(true) ?? "-") : "暂无地址",
            maxLines: 1,
            overflow: TextOverflow.ellipsis,
            style: TextStyle(
              color: Color(0xFFBFC2CC),
              fontSize: 11,
            ),
          ),
        ),
      ],
    );
  }

  String _getNewAddress(bool isCity){
    StringBuffer addressStr = StringBuffer();
    if(widget?.companyBasicInfoBean!=null){
      if((widget.companyBasicInfoBean?.comAddressInfo?.length??0)!=0){
        if(isCity??false){
          addressStr.write(widget.companyBasicInfoBean?.comAddressInfo[0]?.address);
          return addressStr.toString();
        }

        String province = widget.companyBasicInfoBean?.comAddressInfo[0]?.addrProvince;
        String city = widget.companyBasicInfoBean?.comAddressInfo[0]?.addrCity;
        String dirstrict = widget.companyBasicInfoBean?.comAddressInfo[0]?.addrDistrict;
        if (province == city) {
          addressStr.write("$province$dirstrict");
          return addressStr.toString();
        } else {
          addressStr.write("$province$city$dirstrict");
          return addressStr.toString();
        }
      }
    }
  }

  // String _getAddressStr() {
  //   Map<String, ChooseCityListItemBean> _resultLocationMap = Map<String, ChooseCityListItemBean>();
  //   if(UserRepository.getInstance().userData?.companyInfo?.city!=null && UserRepository.getInstance().userData?.companyInfo?.city!=""){
  //     _resultLocationMap = VgLocationUtils.transStringToMap(UserRepository.getInstance().userData?.companyInfo?.city);
  //   }else{
  //     _resultLocationMap =
  //         VgLocationUtils.transStringToMap(UserRepository.getInstance().userData?.companyInfo?.city);
  //   }
  //   if (_resultLocationMap == null || _resultLocationMap.isEmpty) {
  //     return null;
  //   }
  //   String province = _resultLocationMap[CHOOSE_PROVINCE_KEY]?.sname;
  //   String city = _resultLocationMap[CHOOSE_CITY_KEY]?.sname;
  //   String dirstrict = _resultLocationMap[CHOOSE_DISTRICT_KEY]?.sname;
  //   if (province == city) {
  //     return "$province$dirstrict";
  //   } else {
  //     return "$province$city$dirstrict";
  //   }
  // }

  ///企业 数字栏 【管理员】【部门】【未激活】
  _cntCompanyWidget() {
    return Container(
        decoration: BoxDecoration(
            color: Color(0xff303546),
            borderRadius: BorderRadius.only(
                bottomLeft: Radius.circular(12),
                bottomRight: Radius.circular(12))),
        child: Row(children: [
          _cntTextWidget('管理员', widget.infoBean?.topCnt?.adminCnt ?? 0),
          Container(
            width: 0.5,
            height: 18,
            color: VgColors.INPUT_BG_COLOR,
          ),
          _cntTextWidget('部门', widget.infoBean?.topCnt?.departmentCnt ?? 0),
          Visibility(
            visible: UserRepository.getInstance().userData.companyInfo.isShowFaceRecognition(),
            child: Container(
              width: 0.5,
              height: 18,
              color: VgColors.INPUT_BG_COLOR,
            ),
          ),
          Visibility(
            visible: UserRepository.getInstance().userData.companyInfo.isShowFaceRecognition(),
            child: _cntTextWidget('未激活', widget.infoBean?.topCnt?.myUnActiveCnt ?? 0),
          ),

          // _moreWidget(),
        ]));
  }

  ///培训机构展示【管理员】【班级】【部门】【未激活】（未激活为0则不显示【未激活】）
  _cntOrgWidget() {
    return Container(
        decoration: BoxDecoration(
            color: Color(0xff303546),
            borderRadius: BorderRadius.only(
                bottomLeft: Radius.circular(12),
                bottomRight: Radius.circular(12))),
        child: Row(children: [
          _cntTextWidget('管理员', widget.infoBean?.topCnt?.adminCnt ?? 0),

          Container(
            width: 0.5,
            height: 18,
            color: VgColors.INPUT_BG_COLOR,
          ),
          Container(
            width: 0.5,
            height: 18,
            color: VgColors.INPUT_BG_COLOR,
          ),
          _cntTextWidget('班级', widget.infoBean?.topCnt?.classCnt ?? 0),
          Container(
            width: 0.5,
            height: 18,
            color: VgColors.INPUT_BG_COLOR,
          ),
          _cntTextWidget('部门', widget.infoBean?.topCnt?.departmentCnt ?? 0),

          Visibility(
            visible: (widget.infoBean?.topCnt?.myUnActiveCnt ?? 0) > 0 && UserRepository.getInstance().userData.companyInfo.isShowFaceRecognition(),
            child: Container(
              width: 0.5,
              height: 18,
              color: VgColors.INPUT_BG_COLOR,
            ),
          ),
          Visibility(
            visible: (widget.infoBean?.topCnt?.myUnActiveCnt ?? 0) > 0 && UserRepository.getInstance().userData.companyInfo.isShowFaceRecognition(),
            child:
                _cntTextWidget('未激活', widget.infoBean?.topCnt?.myUnActiveCnt ?? 0),
          ),
          // _moreWidget(),
        ]));
  }

  bool isCompany() =>
      UserRepository.getInstance().userData.companyInfo.isCompanyLike();

  ///更多
  _moreWidget() {
    return Visibility(
      //企业项目和城市数 有就显示
      visible: isCompany()
          ? (widget.infoBean.topCnt.cityCnt > 0 || widget.infoBean.topCnt.projectCnt > 0)
          : ((widget.infoBean.topCnt.cityCnt > 0 ||
              widget.infoBean.topCnt.projectCnt > 0 ||
              widget.infoBean.topCnt.departmentCnt > 0)),
      child: Builder(
        builder: (context) {
          return GestureDetector(
            behavior: HitTestBehavior.opaque,
            onTap: () {
              //点击更多
              PopupWindow.showPopWindow(
                  context,
                  "bottom",
                  widget.popKey,
                  PopDirection.bottom,
                  CompanyMorePopWindow(
                    topCnt: widget.infoBean.topCnt,
                    onClick: (text) {
                      onTap(context, text)();
                    },
                  ),
                  -16,
                  0);
            },
            child: Container(
              height: 45,
              child: Row(
                children: <Widget>[
                  Container(
                    width: 0.5,
                    height: 18,
                    color: VgColors.INPUT_BG_COLOR,
                  ),
                  Container(
                    key: widget.popKey,
                    width: 54,
                    alignment: Alignment.center,
                    child: Text(
                      '更多',
                      style: TextStyle(
                          fontSize: 12, color: Color(0xffbfc2cc), height: 0.95),
                    ),
                  )
                ],
              ),
            ),
          );
        },
      ),
    );
  }

  ///顶部数字
  _cntTextWidget(String text, int cnt) {
    return Builder(
      builder: (context) {
        return Expanded(
          child: GestureDetector(
              behavior: HitTestBehavior.opaque,
              onTap: onTap(context, text),
              child: Container(
                height: 45,
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: <Widget>[
                    Text(
                      text,
                      style: TextStyle(
                          fontSize: 12, color: Color(0xffbfc2cc), height: 1),
                    ),
                    SizedBox(
                      width: 8,
                    ),
                    Text(
                      '$cnt',
                      style: TextStyle(
                          fontSize: 12, color: Colors.white, height: 0.9),
                    ),
                  ],
                ),
              )),
        );
      },
    );
  }

  Function onTap(BuildContext context, String text) {
    return () {
      switch (text) {
        case '管理员':
          ManagerListPage.navigatorPush(context);
          break;
        case '未激活':
          UnactivePersonPage.navigatorPush(context);
          break;
        case '部门':
          ClassOrDepartmentPage.navigatorPush(
              context, ClassOrDepartmentPage.TYPE_DEPARTMENT);
          break;
        case '班级':
          ClassOrDepartmentPage.navigatorPush(
              context, ClassOrDepartmentPage.TYPE_CLASS);
          break;
      }
    };
  }
}

enum SelectMode {
  Normal,
  HeadBorder,
}

typedef ClipCompleteCallback = void Function(String path, Function cancelLoadingCallback);

class CompanyPicDetailPage extends StatefulWidget {
  static const ROUTER = "CompanyPicDetailPage";

  final String url;
  final SelectMode selectMode;
  final ClipCompleteCallback clipCompleteCallback;
  final bool isClipCompleteShowLoading;

  const CompanyPicDetailPage({
    Key key,
    this.url,
    this.selectMode,
    this.clipCompleteCallback,
    this.isClipCompleteShowLoading = false,
  }) : assert(url != null && url != "", "url cannot be empty");


  @override
  State<StatefulWidget> createState() => _CompanyLogoState();

  static Future<dynamic> navigatorPush(BuildContext context, {String url, SelectMode selectMode, ClipCompleteCallback clipCompleteCallback}) {
    return RouterUtils.routeForFutureResult(context,
        CompanyPicDetailPage(url: url,
            selectMode: selectMode,
            clipCompleteCallback: clipCompleteCallback),
        routeName: CompanyPicDetailPage.ROUTER);
  }
}

class _CompanyLogoState extends BaseState<CompanyPicDetailPage> {

  String _path;

  @override
  void initState() {
    super.initState();
    _path = widget?.url;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.black,
      body: Column(children: <Widget>[
        _toTopBarWidget(context),
        _buildImageLogo(),
        Container(height: ScreenUtils.getBottomBarH(context))
      ]),
    );
  }

  Widget _toTopBarWidget(BuildContext context) {
    return VgTopBarWidget(
      title: "",
      isShowBack: true,
      backImgColor: Color(0xff5e687c),
      isShowGrayLine: false,
      backgroundColor: Colors.transparent,
      rightPadding: 0,
      rightWidget: Offstage(
        offstage: true,
        child: Container(
            padding: EdgeInsets.symmetric(horizontal: 15, vertical: 10),
            child: Image.asset("images/more_white_dark.png", width: 20, height: 20)
        ),
      ),
    );
  }

  Widget _buildImageLogo() {
    return Expanded(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          Container(
            //这里是点击查看大图图片比例调整
            width: ScreenUtils.screenW(context),
            height: ScreenUtils.screenW(context),
            child: VgCacheNetWorkImage(
              _path,
              fit: BoxFit.contain,
              // width: ScreenUtils.screenW(context),
              // height: ScreenUtils.screenW(context),
              placeWidget: Container(color: Colors.black),
            ),
          ),
          SizedBox(height: 50),
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Visibility(
                visible: VgRoleUtils.isSuperAdmin(UserRepository.getInstance().getCurrentRoleId()),
                child: _buildHandleBtn("更换图片", () => onClickEdit(false))
              )
            ],
          ),
          SizedBox(height: 20)
        ],
      ),
    );
  }

  Future<void> onClickEdit(bool isEdit) async {
    String path = await MatisseUtil.clipOneImage(context, scaleX: 1, scaleY: 1, isCanSelectRadio: true,
        onRequestPermission: (msg)async{
          bool result =
          await CommonConfirmCancelDialog.navigatorPushDialog(context,
            title: "提示",
            content: msg,
            cancelText: "取消",
            confirmText: "去授权",
          );
          if (result ?? false) {
            PermissionUtil.openAppSettings();
          }
        });
    if (path == null || path == "") {
      return;
    }
    _path = path;
    setState(() {});
    RouterUtils.pop(context);
    if (widget?.isClipCompleteShowLoading ?? false) loading(true, msg: "上传中");
    if (widget?.clipCompleteCallback != null) widget?.clipCompleteCallback(_path, () {
      loading(false);
      toast("上传成功");
    });
  }


  Widget _buildHandleBtn(String text, VoidCallback onClickCallback) {
    return ClickAnimateWidget(
      scale: 1.05,
      onClick: onClickCallback ?? (){},
      child: Padding(
        padding: EdgeInsets.symmetric(horizontal: 15, vertical: 20),
        child: Container(
          width: 112,
          height: 40,
          alignment: Alignment.center,
          decoration: BoxDecoration(
              borderRadius: BorderRadius.all(Radius.circular(20)),
              border: Border.all(
                  width: 0.5,
                  color: Color(0xff808388)
              )
          ),
          child: Text(
            "${text ?? ""}",
            style: TextStyle(fontSize: 15,
                color: Color(0xffd0e0f7)
            ),
          ),
        ),
      ),
    );
  }
}
